<template>
	<view class="personal">
		<image class="bg-img" :src="app_img+'/app-img/user1.jpg'"></image>
		<view class="content-wrapper">
			<view class="herder">
				<view style="width: 200rpx;height: 200rpx;margin: 0 auto;margin-bottom: 10rpx;" @tap="chooseImage">
					
					<image :src="imageList.length==0?app_img+'/app-img/avatar1.svg':app_d_img+imageList[0]" mode="" style="width: 200rpx;height: 200rpx;border-radius: 50%;" v-if="form.sex==1" ></image>
					<image :src="imageList.length==0?app_img+'/app-img/avatar2.svg':app_d_img+imageList[0]" mode="" style="width: 200rpx;height: 200rpx;border-radius: 50%;" v-else></image>
				</view>
				<text>选择头像</text>
				<!-- <h1></h1> -->
			</view>
			<view class="personal-form">
				<form >
				<view class="personal-form-items">
					<view class="personal-form-items-title">姓名:</view>
					<input type="text" class="personal-input" placeholder="请输入姓名" name="nickName" v-model="form.nickName"/>
				</view>

				<view class="personal-form-items">
					<view class="personal-form-items-title">性别:</view>
					<view>
						<radio-group class="radio-group" name="type" @change="radioChange"> 
							<label class="radio"><radio  value="1" checked="true" />男</label>
							<label style="margin-left:30rpx;" class="radio"><radio  value="2" />女</label>
						</radio-group>
					</view>
				</view>

				<view class="personal-form-items">
					<view class="personal-form-items-title">邮箱:</view>
					<input type="text" class="personal-input" placeholder="请输入邮箱" name="email" v-model="form.email"/>
				</view>
				<view class="personal-form-items">
					<view class="personal-form-items-title">电话号码:</view>
					<input type="text" class="personal-input" placeholder="请输入电话号码" name="phonenumber" v-model="form.phonenumber"/>
				</view>
				</form >
			</view>
		</view>
		<div class="submit-wrapper">
			<button type="primary" class="personal-btn" @click="onSubmit()" :disabled="personaling">保存</button>
		</div>
	</view>
</template>

<script>
	import {updateAppUser} from '@/api/user.js'
	import graceChecker from "@/common/rulesChecker.js"
	import permision from "@/common/permission.js"
	var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	]
	var sizeType = [
		['compressed'],
		['original'],
		['compressed', 'original']
	]
	export default {
		data() {
			return {
				app_img:this.appimg,
				app_d_img:this.appimg+'/app-img/user',
				img:'',
				sourceTypeIndex: 2,
				imageList: [],
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 2,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 1,
				count: 1,
				form:{
					userId:this.$store.state.user.user.userId,
					nickName:this.$store.state.user.user.nickName,
					file:[],
					sex:this.$store.state.user.user.sex,
					avatar:this.$store.state.user.user.avatar,
					email:this.$store.state.user.user.email,
					phonenumber:this.$store.state.user.user.phonenumber
				},
				personaling:false

			};
		},
		onLoad() {
			this.imageList.push(this.$store.state.user.user.avatar)
		},
		created(){
			
		},
		onUnload() {
			this.imageList = [],
				this.sourceTypeIndex = 2,
				this.sourceType = ['拍照', '相册', '拍照或相册'],
				this.sizeTypeIndex = 2,
				this.sizeType = ['压缩', '原图', '压缩或原图'],
				this.countIndex = 1;
		},
		methods:{
			chooseImage: async function() {
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif
			
				// if (this.imageList.length === 1) {
				// 	let isContinue = await this.isFullImg();
				// 	console.log("是否继续?", isContinue);
				// 	if (!isContinue) {
				// 		return;
				// 	}
				// }
				uni.chooseImage({
					sourceType: sourceType[this.sourceTypeIndex],
					sizeType: sizeType[this.sizeTypeIndex],
					//count: this.imageList.length + this.count[this.countIndex] > 1 ? 1 - this.imageList.length : this.count[this.countIndex],
					count:this.count,
					success: (res) => {
						this.imageList=[]
						this.imageList = this.imageList.concat(res.tempFilePaths);
						console.log(this.imageList)
						this.app_d_img=[]
						this.form.file=res.tempFilePaths
					},
					fail: (err) => {
						console.log("err: ",err);
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						if(err.errMsg.indexOf('cancel') !== '-1'){
							return;
						}
						uni.getSetting({
							success: (res) => {
								let authStatus = false;
								switch (this.sourceTypeIndex) {
									case 0:
										authStatus = res.authSetting['scope.camera'];
										break;
									case 1:
										authStatus = res.authSetting['scope.album'];
										break;
									case 2:
										authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
										break;
									default:
										break;
								}
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
						// #endif
					}
				})
			},
			async checkPermission(code) {
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');
			
				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}
			
				return status;
			},
			radioChange(e){
				this.form.sex=e.detail.value
			},
			 onSubmit(e) {  
				var rule = [
				    {name:"nickName", checkType : "zw", checkRule:"",  errorMsg:"姓名不能为空",ruleMsg:"姓名格式错误"},
				    // {name:"sex", checkType : "in", checkRule:"男,女",  errorMsg:"请选择性别"},
				    {name:"email", checkType : "email", checkRule:"",  errorMsg:"邮箱不能为空",ruleMsg:"邮箱格式错误"},
					{name:"phonenumber", checkType : "phoneno", checkRule:"",  errorMsg:"电话号码不能为空",ruleMsg:"电话号码格式错误"}
				];
				//进行表单检查
				var formData = this.form;
				console.log(formData,this.form.file)
				var checkRes = graceChecker.check(formData, rule);
				if(checkRes){
					if(this.form.file.length==0){
						updateAppUser(formData).then(res=>{
							uni.showToast({title:"修改成功!", icon:"none"});
						})
					}else{
						uni.uploadFile({
				    		url:this.$axios+'/modify-data', //从调用页面传入 -- url: 'http://127.0.0.1:3000/' 后端接口地址
				    		filePath: this.form.file[0], //从调用页面传入 --path: imgbox, 选取图片的地址数组  
				    		name: 'file', //文件名称可以自定义，要与后端配对使用：app.post('/',upload.single('img'),function(req,res,next)
				    		formData: {  //这里是上传图片时一起上传的数据
				    			userName:this.form.userName,
				    			password:this.form.password,
				    			nickName:this.form.nickName,
								userId:this.form.userId,
								avatar:this.form.userId,
				    			sex:this.form.sex,
				    			email:this.form.email,
				    			phonenumber:this.form.phonenumber
				    		},
				    		header:{
				    			"Content-Type": "multipart/form-data",
								"Authorization":'Bearer '+uni.getStorageSync('token')
				    		},
				    		success: (res) => {
				    			console.log(JSON.parse(res.data).code) 
				    			if(JSON.parse(res.data).code==200){
				    				uni.showToast({title:"修改成功!", icon:"none"});
				    			}else if(JSON.parse(res.data).code==500){
				    				uni.showToast({title:JSON.parse(res.data).msg, icon:"none"});
				    
				    			}
				    			
				    		},
				    
				    		fail: (res) => {  //失败
				    		},
				    		complete: () => { //不论成功、失败都执行		
				    			
				    		}
				        });
					}
				}else{
					console.log(graceChecker)
				    uni.showToast({ title: graceChecker.error, icon: "none" });
				}
			} 
			
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background: #F4F5F6;
	}
	.personal {
		.content-wrapper {
			width: 100%;

			.herder {
				margin-top: 35rpx;
				width: 100%;
				margin-bottom: 10px;
				text-align: center;

				h1 {
					border: 0px;
					width: 50%;
					margin: 0 auto;
					text-align: center;
					border-bottom: 1px solid #E3E3E3;
					height: 50px;
					line-height: 50px;
					font-size: 17px;
					overflow: hidden;
					font-weight: 400;
				}
			}

			.personal-form {
				margin: 10px 10px 20px 15px;
				//background: #FFFFFF;

				.personal-form-items {
					padding: 15px 10px;
					border-bottom: 1px solid #F3F4F5;
					position: relative;
					display: -webkit-flex;
					display: flex;

					.personal-form-items-title {
						width: 30%;
						line-height: 22px;
						height: 22px;
						flex-shrink: 0;
					}

					.personal-input {
						width: 100%
					}

					img {
						width: auto;
						height: auto;
						max-width: 100%;
						max-height: 100%;
					}
				}
			}
		}

		.submit-wrapper {
			padding: 10px;
			padding-top: 10px;
		}

	}
</style>

